package com.arpa.oms.service.impl;


import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.ntocc.common.common.cache.PartyCache;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.oms.domain.dto.OmsOrderSetDTO;
import com.arpa.oms.domain.entity.OmsOrderSet;
import com.arpa.oms.domain.vo.OmsOrderSetVO;
import com.arpa.oms.mapper.OmsOrderSetMapper;
import com.arpa.oms.service.IOmsOrderSetService;
import com.arpa.wms.cache.ShopCache;
import com.arpa.wms.common.util.SourcePlatformUtils;
import com.arpa.wms.common.util.UUIDUtil;
import com.arpa.wms.domain.enums.StatusEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: rfwang
 * @Date 2021/8/10
 * @Description:
 */
@Service
public class OmsOrderSetServiceImpl extends ServiceImpl<OmsOrderSetMapper, OmsOrderSet> implements IOmsOrderSetService {

    @Autowired
    private PartyCache partyCache;
    @Autowired
    private ShopCache shopCache;
    private static final Integer SIXTY = 60;
    private static final Integer ONE_THOUSAND_FOUR_HUNDREN_AND_FORTY = 1440;
    /**
     * 查询列表
     *
     * @param orderSetDTO
     * @return
     */
    @Override
    public List<OmsOrderSetVO> queryList(OmsOrderSetDTO orderSetDTO) {
        List<OmsOrderSetVO> customerVOList = baseMapper.queryList(orderSetDTO);
        return customerVOList;
    }

    /**
     * 查询合计,包含总数
     *
     * @param orderSetDTO
     * @return
     */
    @Override
    public OmsOrderSetVO queryListSum(OmsOrderSetDTO orderSetDTO) {
        OmsOrderSetVO customerVO = baseMapper.queryListSum(orderSetDTO);
        return customerVO;
    }

    /**
     * 保存
     * @param entity
     * @return
     */
    @Override
    @Transactional(rollbackFor={Exception.class})
    public boolean save(OmsOrderSet entity) {
        //校验同一个货主，同一个平台，同一个店铺，是否只有一个店铺
        validateOrderSet(entity);
        if(StringUtils.isBlank(entity.getCode())){
            entity.setCode(UUIDUtil.getUUID32());
        }
        if (StrUtil.isEmpty(entity.getPlatformName())) {
            entity.setPlatformName(SourcePlatformUtils.translate(entity.getPlatformCode()));
        }
        if (StrUtil.isEmpty(entity.getShopName())) {
            entity.setShopName(shopCache.translate(entity.getShopCode()));
        }
        if(StringUtils.isBlank(entity.getCreatedBy())){
            entity.setCreatedBy(UserUtil.getCode());
            entity.setCreatedName(partyCache.translate(UserUtil.getCode()));
            entity.setModifiedBy(UserUtil.getCode());
            entity.setModifiedName(partyCache.translate(UserUtil.getCode()));
        }
        entity.setCron(generateCron(entity.getInteval()));
        return super.save(entity);
    }

    private String generateCron(String inteval) {
        String hourStr = StrUtil.EMPTY;
        String minuteStr = StrUtil.EMPTY;
        Integer intevalTime = Integer.parseInt(inteval);
        //超过一个小时的，舍掉分钟取整小时调用
        if (intevalTime >= SIXTY) {
            hourStr =  intevalTime/SIXTY + "";
        } else {
            minuteStr = inteval;
        }
        StringBuilder cronExp = new StringBuilder();
        cronExp.append("0 ");
        if (StrUtil.isNotEmpty(minuteStr)) {
            cronExp.append("*/").append(minuteStr);
            cronExp.append(" ");
            cronExp.append("* ");
        } else {
            cronExp.append("0 ");
            cronExp.append("*/").append(hourStr);
            cronExp.append(" ");
        }
        cronExp.append("* ");
        cronExp.append("* ");
        cronExp.append("?");
        return cronExp.toString();
    }
    private void validateOrderSet(OmsOrderSet entity) {
        //必填项校验
        if (entity == null) {
            throw new ServiceException("新增接单设置不能为空");
        }
        if (StrUtil.isEmpty(entity.getPlatformCode())) {
            throw new ServiceException("平台必填，不能为空");
        }
        if (StrUtil.isEmpty(entity.getShopCode())) {
            throw new ServiceException("店铺必填，不能为空");
        }
        if (StrUtil.isEmpty(entity.getInteval())) {
            throw new ServiceException("时间间隔必填，不能为空");
        }
        try {
            Integer inteval = Integer.parseInt(entity.getInteval());
           if (inteval > ONE_THOUSAND_FOUR_HUNDREN_AND_FORTY) {
               throw new ServiceException("时间间隔不能超过24小时");
           }
       } catch(Exception e) {
           throw new ServiceException("所填数值非整数");
       }


        OmsOrderSet omsOrderSet = this.getOne(new LambdaQueryWrapper<OmsOrderSet>()
                .eq(OmsOrderSet::getShipmentCode, entity.getShipmentCode())
                .eq(OmsOrderSet::getPlatformCode, entity.getPlatformCode())
                .eq(OmsOrderSet::getShopCode, entity.getShopCode()));
        //如果是修改，根据货主、平台、店铺查询出的订单设置排除自身后，如果已经存在，则报错
        if (StrUtil.isNotEmpty(entity.getCode()) && omsOrderSet != null) {
            if (entity.getCode().equals(omsOrderSet.getCode())) {
                omsOrderSet = null;
            }
        }
        if (omsOrderSet != null) {
            throw new ServiceException("入驻商" + omsOrderSet.getShipmentName() + ",平台" + omsOrderSet.getPlatformName() + ",店铺"
                    + omsOrderSet.getShopName() + "已新增接单设置，请确认" );
        }
    }

    /**
     * 根据code更新实体
     * @param entity
     * @return
     */
    @Override
    @Transactional(rollbackFor={Exception.class})
    public int updateByCode(OmsOrderSet entity) {
        //校验同一个货主，同一个平台，同一个店铺，是否只有一个店铺
        validateOrderSet(entity);
        entity.setCron(generateCron(entity.getInteval()));
        if(StringUtils.isBlank(entity.getModifiedBy())){
            entity.setModifiedBy(UserUtil.getCode());
            entity.setModifiedName(partyCache.translate(UserUtil.getCode()));
        }
        if (StrUtil.isEmpty(entity.getPlatformName())) {
            entity.setPlatformName(SourcePlatformUtils.translate(entity.getPlatformCode()));
        }
        if (StrUtil.isEmpty(entity.getShopName())) {
            entity.setShopName(shopCache.translate(entity.getShopCode()));
        }
        return baseMapper.update(entity,new QueryWrapper<OmsOrderSet>().lambda().eq(OmsOrderSet::getCode,entity.getCode()));
    }

    /**
     *  根据code更新启用、停用状态
     * @param codes
     * @param active
     * @return
     */
    @Override
    public Map<String,Object> activeStatus(List<String> codes, StatusEnum active) {
        Map<String,Object> result= new HashMap<>();
        int num = updateStatus(codes,active);
        result.put("success",num);
        return result;
    }

    private int updateStatus(List<String> optCodes,StatusEnum active){
        int num = 0;
        boolean flag = false;
        if(IterUtil.isNotEmpty(optCodes)){
            for(String code: optCodes){
                flag = this.update(new UpdateWrapper<OmsOrderSet>().lambda().set(OmsOrderSet::getStatus, active.getValue())
                        .eq(OmsOrderSet::getCode, code));
                if(flag){
                    num++;
                }
            }
        }
        return num;
    }

}
